<?php

use Illuminate\Support\Facades\Cache;

/**
 * @param        $file 上传的文件name
 * @param string $path 文件保存路径
 * @param array  $allowType 允许上传的文件格式
 * @param bool   $timePath 是否根据当前日期生成子目录
 * @return array
 */
if (!function_exists('uploadFile')) {
	function uploadFile($file, $path = "upload", $allowType = [], $timePath = true)
	{
		//判断请求中是否包含name=file的上传文件
		if (!request()->hasFile($file)) {
			$data = ['status_code' => 500, 'message' => '上传文件为空'];
			return $data;
		}
		$to_up_file = request()->file($file);
		//是否上传成功
		if (!$to_up_file->isValid()) {
			$data = ['status_code' => 500, 'message' => '上传文件出错'];
			return $data;
		}
		//是否生成日期目录
		if ($timePath === true) {
			$path = './' . trim($path, './') . '/' . date('Ymd') . '/';
		} else {
			$path = './' . trim($path, './') . '/';
		}
		//是否存在此文件夹，
		if (!is_dir($path)) {
			mkdir($path, 0755, true);
		}
		//上传的文件名
		$file_name = $to_up_file->getClientOriginalName();
		//文件后缀
		$file_ext = $to_up_file->getClientOriginalExtension();
		if ($allowType && !in_array($file_ext, $allowType)) {
			$data = ['status_code' => 500, 'message' => '上传文件类型不符'];
			return $data;
		}
		//新文件名
		$new_file_name = uniqid() . '.' . $to_up_file->getClientOriginalExtension();
		//上传失败
		if (!$to_up_file->move($path, $new_file_name)) {
			$data = ['status_code' => 500, 'message' => '保存失败'];
			return $data;
		}
		//成功上传,
		$data = ['status_code' => 200, 'message' => '上传成功', 'url' => (trim($path, ".")) . $new_file_name];
		return $data;
	}
}
if (!function_exists('mydump')) {
	function mydump($s)
	{
		if (is_object($s)) {
			$s = $s->toArray();
		}
		var_dump($s);
		exit;
	}
}

if (!function_exists('sys')) {
	function sys(string $key)
	{
		$cache = Cache::store('file')->get('settings');
		if (!$cache) {
			Cache::store('file')->forever('settings', \App\Models\Setting::pluck('value', 'name'));
		}
		return isset($cache[$key]) ? $cache[$key] : '';
	}
}


